// 知识库状态管理 - Pinia Store
import { ref } from 'vue'
import { defineStore } from 'pinia'
import {createKnowledgeAPI, getKnowledgeListAPI} from "@/api/knowledge.ts";
import {getUserId} from "@/utils/auth.ts";


export const useKnowledgeStore = defineStore('knowledge', () => {
  // 知识库列表
  const knowledgeList = ref<any[]>([

  ])

  // 获取知识库列表
  const fetchKnowledgeList = async () => {
    

    try {
      const result = await getKnowledgeListAPI(<string>getUserId())
      knowledgeList.value = Array.isArray(result) ? result : result.knowledge_list
      console.log("知识库列表已更新:", knowledgeList.value)
    } catch (error) {
      console.error("Failed to fetch knowledge list:", error)
      knowledgeList.value = []
    }

  }

  // 删除知识库
  const deleteKnowledge = async (id: string) => {
    console.log(`尝试删除ID为 ${id} 的知识库...`)
    const index = knowledgeList.value.findIndex(item => item.id === id)
    if (index !== -1) {
      knowledgeList.value.splice(index, 1)
      console.log(`ID ${id} 已被删除。`)
    } else {
      console.warn(`未找到ID为 ${id} 的知识库。`)
    }
    
  }

  const createKnowledge = async (data: { name: string, ownerId: string }) => {
    // 创建知识库
    console.log('创建新的知识库:', data)

    try {
      const newKnowledgeData = {
        name: data.name,
        ownerId: data.ownerId,
        cover_url: '/cover.png'
      }
      const result = await createKnowledgeAPI(newKnowledgeData)
      const newKnowledge = {
        ...result,
        cover_url: '/cover.png'
      };
      knowledgeList.value.unshift(newKnowledge)
    } catch (error) {
      console.error("Failed to create knowledge:", error)
    }
    // const newKnowledge = {
    //   id: `kb_${Date.now()}`, // 临时生成唯一ID
    //   name: data.name,
    //   cover_url: data.coverUrl,
    //   docs: []
    // }
    // knowledgeList.value.unshift(newKnowledge); // 添加到列表开头
  }

  const editKnowledge = async (data: { id: string, name: string }) => {
    // 编辑知识库
    console.log('编辑知识库:', data);
    const index = knowledgeList.value.findIndex(item => item.id === data.id);
    if (index !== -1) {
      knowledgeList.value[index] = { ...knowledgeList.value[index], ...data };
    }
  }

  return {
    knowledgeList,
    fetchKnowledgeList,
    deleteKnowledge,
    createKnowledge,
    editKnowledge
  }
}) 